﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Newtor.VoteMan.Providers
{
    public class LinqVoteItemManager : IVoteItemManager
    {
        #region IVoteItemManager 成员

        public VoteItem[] GetItemsByProjectId(Guid projectId)
        {
            using (VoteDataContext vdc = new VoteDataContext())
            {
                return (from vi in vdc.VoteItem
                        where vi.ProjectId == projectId
                        orderby vi.Order
                        select vi).ToArray();
                //return vdc.VoteProject.Single(p => p.ProjectId == projectId).Items.ToArray();
            }
        }

        public VoteItem GetVoteItem(Guid viId)
        {
            using (VoteDataContext vdc = new VoteDataContext())
            {
                try
                {
                    return vdc.VoteItem.Single(v => v.ItemId == viId);
                }
                catch (InvalidOperationException)
                {
                    return null;
                }
            }
        }

        public void CreateVoteItem(VoteItem vi)
        {
            using (VoteDataContext vdc = new VoteDataContext())
            {
                vdc.VoteItem.InsertOnSubmit(vi);
                vdc.SubmitChanges();
            }
        }

        public void UpdateVoteItem(VoteItem vi)
        {
            using (VoteDataContext vdc = new VoteDataContext())
            {
                var oldVi = vdc.VoteItem.Single(v => v.ItemId == vi.ItemId);
                oldVi.Name = vi.Name;
                oldVi.Order = vi.Order;
                oldVi.ProjectId = vi.ProjectId;
                vdc.SubmitChanges();
            }
        }


        public VoteItem[] GetItemsIncludeSubProjects(Guid projectId)
        {
            List<VoteItem> items = new List<VoteItem>();
            using (VoteDataContext vdc = new VoteDataContext())
            {
                VoteProject vp;
                try
                {
                    vp = vdc.VoteProject.Single(p => p.ProjectId == projectId);
                }
                catch (InvalidOperationException)
                {
                    return items.ToArray();
                }
                
                items.AddRange(vp.Items.OrderBy(vi => vi.Order));
                var subProjects = from sp in vp.SubProjects
                                  orderby sp.Order
                                  select sp;

                foreach (var subProject in subProjects)
                {
                    items.AddRange(GetItemsIncludeSubProjects(subProject.ProjectId));
                }
                return items.ToArray();
            }
        }

        #endregion
    }
}